/**
 * 颜色工具
 * @author luguoxiang
 * @date 2021-09-07
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */

/**
 * rag 颜色 转 十六进制颜色
 * @param r
 * @param g
 * @param b
 */
export function rgbToHex(r: number, g: number, b: number) {
  const r1 = `0${(r || 0).toString(16)}`.slice(-2);
  const g1 = `0${(g || 0).toString(16)}`.slice(-2);
  const b1 = `0${(b || 0).toString(16)}`.slice(-2);
  return `#${r1}${g1}${b1}`;
}

/**
 * 十六进制颜色转rgb值
 * @param hexColor
 */
export function hexToRgb(hexColor: string) {
  const r: number = parseInt(hexColor.substring(1, 3), 16);
  const g: number = parseInt(hexColor.substring(3, 5), 16);
  const b: number = parseInt(hexColor.substring(5, 7), 16);
  return [r, g, b];
}

/**
 * 渐变色计算
 * @param color1 原色
 * @param color2 目标颜色
 * @param weight 权重（0 ~ 1），权重越大越接近目标颜色
 */
export function colorCalc(color1: string, color2: string, weight: number) {
  // 权重范围控制
  if (weight < 0) {
    weight = 0;
  } else if (weight > 1) {
    weight = 1;
  }
  // 色值转换
  const r1: number = parseInt(color1.substring(1, 3), 16);
  const g1: number = parseInt(color1.substring(3, 5), 16);
  const b1: number = parseInt(color1.substring(5, 7), 16);
  const r2: number = parseInt(color2.substring(1, 3), 16);
  const g2: number = parseInt(color2.substring(3, 5), 16);
  const b2: number = parseInt(color2.substring(5, 7), 16);
  // 权重计算
  return rgbToHex(
    Math.round(r1 * (1 - weight) + r2 * weight),
    Math.round(g1 * (1 - weight) + g2 * weight),
    Math.round(b1 * (1 - weight) + b2 * weight),
  );
}

/**
 * 褪色（使颜色变淡）
 * @param color
 * @param opacity
 */
export function fade(color: string, opacity: number) {
  opacity = Math.round(255 * opacity);
  const s = opacity.toString(16);
  return color + (s.length < 2 ? `0${s}` : s);
}
